/*
 * @Description: 加载更多
 * @Author: seadon
 * @LastEditors: seadon
 * @Date: 2021-07-13 15:25:45
 * @LastEditTime: 2021-07-19 14:28:20
 */
import { DirectiveBinding, ObjectDirective } from 'vue'

function scrollDom(el: HTMLElement, binding: DirectiveBinding) {
	const scrollDom: any = el.querySelector('.ant-table-body') ?? el.firstChild
	let timer: any
	let isTrue = true
	scrollDom.onscroll = () => {
		if (isTrue) {
			clearTimeout(timer)
			timer = setTimeout(() => {
				const scrollTop = scrollDom?.scrollTop
				const clientHeight = scrollDom?.clientHeight
				const scrollHeight = scrollDom?.scrollHeight
				if (scrollTop + clientHeight > scrollHeight - 20) {
					isTrue = false
					try {
						binding.value().then(() => {
							isTrue = true
						})
					} catch (err) {
						if (
							String(err).includes(`Cannot read property 'then' of undefined`)
						) {
							throw Error(`${binding.value?.name} is not <Promise> object`)
						} else {
							throw err
						}
					}
				}
			}, 100)
		}
	}
}

const loadingMore: ObjectDirective = {
	mounted(el, binding) {
		scrollDom(el, binding)
	},
	beforeUnmount(el, binding) {
	},
}

export default loadingMore
